package top.callback.inf.beautyleaf.common.thread;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常受控的线程任务。基于 Runnable 扩展，提供了异常处理回调机制。
 *
 * @author Pengyu Gan
 * Created 2021/3/23
 */
@Slf4j
public class MonitoredRunnable implements Runnable {

    private Runnable run;

    private RunnableExceptionHandler callback;

    public MonitoredRunnable(Runnable run, RunnableExceptionHandler callback) {
        if (null == callback) {
            throw new IllegalArgumentException("callback can not be null");
        }
        this.run = run;
        this.callback = callback;
    }

    @Override
    public void run() {
        try {
            run.run();
        } catch (Throwable t) {
            callback.handle(t);
        }
    }

}
